package directory_sync;

import java.awt.Color;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFileChooser;

public class SyncSelector
{
	private static final Color RED = new Color(205, 55, 0);
	private static final Color BLACK = new Color(0, 0, 0);
	
	private DisplayMain display;
	
	public SyncSelector(DisplayMain aDisplay)
	{
		display = aDisplay;
	}
	
	protected String readDirectory(String title)
	{
		String folder = "";
		JFileChooser chooseFolder = new JFileChooser();
		chooseFolder.setCurrentDirectory(new java.io.File("C:/"));
		chooseFolder.setDialogTitle(title);
		chooseFolder.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		chooseFolder.setMultiSelectionEnabled(false);
	    int optionFile = chooseFolder.showOpenDialog(display);
	    if(optionFile == JFileChooser.APPROVE_OPTION)
	    {
	    	File selectedFile = chooseFolder.getSelectedFile();
	    	folder = selectedFile.getPath();
			display.setStatusLabel("Directory \"" + folder + "\" chosen.", BLACK);
	    }
	    else if(optionFile == JFileChooser.CANCEL_OPTION)
	    {
			display.setStatusLabel("No directory chosen.", RED);
	    }
	    return folder;
	}
	
	protected void showDirectory(String folder, int tableIdentifier)
	{
		File directory = new File(folder);
		String[] children = directory.list();
		Object[] attributes = new Object[4];
		for(int i=0; i<children.length; i++)
		{
			String filePath = folder + "/" + children[i];
			File fileObj = new File(filePath);
			attributes[0] = fileObj.getName();
			if(fileObj.isFile())
			{
				int position = 0;
				String name = fileObj.getName();
				position = name.lastIndexOf(".");
				if(position!=-1)
				{
					attributes[1] = "file ("+name.substring(position).toLowerCase()+")";
				}
				else
				{
					attributes[1] = "file (-)";
				}
			}
			else
			{
				attributes[1] = "directory";
			}
			if(fileObj.isFile())
			{
				attributes[2] = (fileObj.length()/1024)+" KB";
			}
			else
			{
				attributes[2] = "";
			}
			SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy [HH:mm]");
			Date date = new Date(fileObj.lastModified());
			attributes[3] = dateFormat.format(date);
			display.addRowToTable(attributes, tableIdentifier);
		}
	}
}